#include "texture.h"

#include <string>
#include <iostream>
#include "../lodepng.h"
#include "texturemanager.h"
#include "gl/gl.h"
#include "../graphicsmanager.h"
using namespace std;

Texture::Texture(string location) : Image(0, 0), Location(), Name(), ID(0), XOffset(0), YOffset(0) {
	init(location);
}

Texture::Texture(string location, int x, int y) : Image(0, 0), Location(), Name(), ID(0), XOffset(x), YOffset(y){
	init(location);
}

Texture::~Texture(){
	glDeleteTextures(1, &ID);
}

void Texture::init(string location){
	//load and decode
	std::vector<unsigned char> image;
	unsigned width, height;
	unsigned error = lodepng::decode(image, width, height, location);

	//if there's an error, display it
	if(error){
		//throw "decoder error" << error << ": " << lodepng_error_text(error) << std::endl;
		//throw lodepng_error_text(error);
		printf("%s\n", lodepng_error_text(error));
	}

	//printf("%i", image[1]);
	this->ID = TextureManager::CreateTextureFromPNG(image, width, height);
	//this->ID = TextureManager::CreateTextureFromPNG(image, width, height);
	this->Width = width;
	this->Height = height;

	//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}

void Texture::Draw(double x, double y){
	this->Draw(x, y, Width, Height);
}
void Texture::Draw(double x, double y, double width, double height){
	double x1 = x;
	double y1 = y;
	double x2 = x + width;
	double y2 = y + height;
	glColor3d(1, 1, 1);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, ID);
	glBegin(GL_QUADS);
		glTexCoord2d(0.0, 0.0); glVertex2d(x1, y1);
		glTexCoord2d(1.0, 0.0); glVertex2d(x2, y1);
		glTexCoord2d(1.0, 1.0); glVertex2d(x2, y2);
		glTexCoord2d(0.0, 1.0); glVertex2d(x1, y2);
	glEnd();
}
